/*
 * 项 目 名  :   chopstickshealth
 * 作      者  :  Li Jun
 * 类      名  :  UpdateManager.java
 * 包      名  :  com.dw.chopstickshealth.update.UpdateManager
 * 当前修改时间 :  2019年08月23日 13:07:58
 * 上次修改时间 :  2019年08月23日 13:05:49
 * Copyright (c) 2019  重庆中联信息产业有限责任公司 http://www.zlsoft.com
 */

package com.zlsoft.web.utils;


import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.text.TextUtils;
import android.widget.Toast;

import com.azhon.appupdate.manager.DownloadManager;
import com.google.gson.Gson;
import com.google.zxing.common.StringUtils;
import com.hjq.http.EasyHttp;
import com.hjq.http.listener.HttpCallback;
import com.hjq.http.listener.OnHttpListener;
import com.qqz.common.AppInfoBean;
import com.qqz.common.HttpData;
import com.zlsoft.mobilenurse.R;
import com.zlsoft.web.bean.AppInfoResponseBean;
import com.zlsoft.web.bean.BuildObject;
import com.zlsoft.web.bean.CheckVersionResult;
import com.zlsoft.web.ui.activity.MainActivity;
import com.zlsoft.web.ui.activity.UpdateAppDialog;
import com.zlsoft.web.utils.permissions.PermissionsUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by James on 2018/3/28 0028.
 */

public class UpdateManager {

    public static int currentVersion = 1;

    private static String currentUpdateSiteId = "";

//    private static UpdateBuilder builder;

    private static PackageInfo mPackageInfo = null;


    public static void checkVersion(Activity context) {
        DownloadManager manager = new DownloadManager.Builder(context).apkUrl("www.zlsoft.com/file/download/202039458.apk").apkName("appupdate.apk").smallIcon(R.drawable.ic_zlsoft_logo)
                //设置了此参数，那么内部会自动判断是否需要显示更新对话框，否则需要自己判断是否需要更新
                .apkVersionCode(21)
                //同时下面三个参数也必须要设置
                .apkVersionName("v4.2.2").apkSize("7.7MB").apkDescription("移动护理")
                //省略一些非必须参数...
                .build();
        manager.download();
    }


//    private static UpdateConfig createUpdateConfig(Context context) {
//        //当前版本号
//        PackageInfo packageInfo = null;
//        try {
//            packageInfo = context.getApplicationContext()
//                    .getPackageManager()
//                    .getPackageInfo(context.getPackageName(), 0);
//        } catch (PackageManager.NameNotFoundException e) {
//            e.printStackTrace();
//        }
//        currentVersion = packageInfo.versionCode;
//
//        builder = UpdateBuilder.create();
//
//        builder.setUpdateParser(new UpdateParser() {
//            @Override
//            public Update parse(String response) throws Exception {
//                Update mUpdate = new Update();
//                mUpdate.setVersionCode(18);
//                mUpdate.setUpdateUrl("www.zlsoft.com/file/download/202039458.apk");
//                mUpdate.setForced(true);
//                mUpdate.setIgnore(true);
//                mUpdate.setUpdateContent("message");
//                mUpdate.setVersionName("sf");
//                builder.getUpdateChecker().check(mUpdate);
//                return mUpdate;
//            }
//        }).setUpdateChecker(new UpdateChecker() {
//            @Override
//            public boolean check(Update update) throws Exception {
//                CheckNotifier notifier = builder.getCheckNotifier();
//                notifier.setBuilder(builder);
//                notifier.setUpdate(update);
//                return true;
//            }
//        }).setUpdateStrategy(new UpdateStrategy() {
//            @Override
//            public boolean isShowUpdateDialog(Update update) {
//                return true;
//            }
//
//
//            @Override
//            public boolean isShowDownloadDialog() {
//                return true;
//            }
//
//
//            @Override
//            public boolean isAutoInstall() {
//                return true;
//            }
//        });
//        ;
//
//        UpdateParser jsonParser = builder.getUpdateParser();
//        try {
//            Update update = jsonParser.parse("ok");
//        } catch (Exception mE) {
//            mE.printStackTrace();
//        }
//
//        return new UpdateConfig();
//
//    }

    public static void cInit(MainActivity mLaunchActivity, String mParams) {
        PermissionsUtils.getInstance().getPermission(mLaunchActivity, mB -> {
            checkUpdate(mLaunchActivity, mParams);
        });
    }

    public static void downloadApp(MainActivity activity,String url){
        CheckVersionResult mDescription = new CheckVersionResult(url, 0, "app", "2024-11-11", "description", 0);
        new UpdateAppDialog(activity, mDescription, activity).show();
    }


    private static void checkUpdate(MainActivity mLaunchActivity, String mParams) {
        BuildObject dynamicParams = JsonUtil.stringToObject(mParams, BuildObject.class);
        String[] mSplit = dynamicParams.name.split(",");
        List<BuildObject> mArrayList = new ArrayList<>();
        if (mSplit.length != 0) {
            for (int mI = 0; mI < mSplit.length; mI++) {
                BuildObject mBuildObject = new BuildObject();
                mBuildObject.name = mSplit[mI];
                mBuildObject.org_id = dynamicParams.org_id;
                mBuildObject.dept_id = dynamicParams.dept_id;
                mBuildObject.staff_id = dynamicParams.staff_id;
                mArrayList.add(mBuildObject);
            }
        } else {
            Toast.makeText(mLaunchActivity, "param ex", Toast.LENGTH_SHORT).show();
        }

        try {
            mPackageInfo = mLaunchActivity.getApplicationContext().getPackageManager().getPackageInfo(mLaunchActivity.getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        if (!TextUtils.isEmpty(dynamicParams.host) && !TextUtils.isEmpty(dynamicParams.api)) {

            EasyHttp.post(mLaunchActivity).server(dynamicParams.host).api(dynamicParams.api)

                    .json(new Gson().toJson(mArrayList)).request(new HttpCallback<HttpData<List<AppInfoBean.DataBean>>>(new OnHttpListener() {
                        @Override
                        public void onSucceed(Object result) {
                            try {
                                AppInfoResponseBean mAppInfoResponseBean = JsonUtil.stringToObject(JsonUtil.objectToJsonString(result), AppInfoResponseBean.class);
                                AppInfoResponseBean.DataBean mDataA = mAppInfoResponseBean.data.get(0);
                                AppInfoResponseBean.DataBean mDataB = mAppInfoResponseBean.data.get(1);

                                int mVersionCode = mPackageInfo.versionCode;

                                if (Integer.parseInt(mDataB.value) > mVersionCode) {
                                    CheckVersionResult mDescription = new CheckVersionResult(mDataA.value, Integer.parseInt(mDataB.value), mDataB.name, "2021-11-11", "description", 0);
                                    new UpdateAppDialog(mLaunchActivity, mDescription, mLaunchActivity).show();
                                }
                            } catch (Exception e) {
                                Toast.makeText(mLaunchActivity, "01参数解析失败", Toast.LENGTH_SHORT).show();
                            }
                        }

                        @Override
                        public void onFail(Exception e) {
                            Toast.makeText(mLaunchActivity, "检查更新接口异常" + e.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }));
        }else{
            Toast.makeText(mLaunchActivity, "host or api is null", Toast.LENGTH_SHORT).show();
        }
    }
}
